package hu.mapro.gwtui.gxt.client.data;

import java.util.List;

import com.google.gwt.core.client.Callback;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.RequestContext;
import com.google.web.bindery.requestfactory.shared.ServerFailure;
import com.sencha.gxt.data.shared.loader.DataProxy;
import com.sencha.gxt.data.shared.loader.PagingLoadConfig;
import com.sencha.gxt.data.shared.loader.PagingLoadResult;
import com.sencha.gxt.data.shared.loader.PagingLoadResultBean;

/**
 * An abstract request factory proxy that supports processing results using
 * either a RPC style <code>Callback</code> or a <code>RequestFactory</code>
 * <code>Receiver</code>.
 * 
 * @param <C>
 *            the type of data used to configure the load from the proxy
 * @param <D>
 *            the type of data being returned by the data proxy
 */
public abstract class PageLoadRequestFactoryProxy<D, R extends RequestContext> implements
		DataProxy<PagingLoadConfig, PagingLoadResult<D>>, PageLoadActions<D, R> {
	
	
	public final void load(PagingLoadConfig loadConfig,
			final Callback<PagingLoadResult<D>, Throwable> callback) {

		final PagingLoadResultBean<D> plr = new PagingLoadResultBean<D>();
		plr.setOffset(loadConfig.getOffset());
		
		R requestContext = createRequestContext();
		createCountRequest(requestContext).to(new Receiver<Long>() {
			@Override
			public void onSuccess(Long response) {
				plr.setTotalLength(response.intValue());
			}
		});
		createListRequest(requestContext, loadConfig).to(new Receiver<List<D>>() {
			@Override
			public void onSuccess(List<D> response) {
				plr.setData(response);
			}
		});
		
		requestContext.fire(new Receiver<Void>() {
			@Override
			public void onFailure(ServerFailure error) {
				callback.onFailure(new RuntimeException(error.getMessage()));
			}
			@Override
			public void onSuccess(Void response) {
				callback.onSuccess(plr);
			}
		});
		
		
	}
	
}
